package com.qigao.mall.channel.alipay;

import com.alibaba.fastjson.JSONObject;
import com.qigao.mall.channel.ChannelCore;
import com.qigao.mall.channel.config.ChannelConstant;
import com.qigao.mall.channel.dto.ChannelQueryRespDto;
import com.qigao.mall.commons.dto.MerChannelDto;
import com.qigao.mall.commons.enums.*;
import com.qigao.mall.commons.param.ChannelReqParam;
import com.qigao.mall.commons.param.ChannelRespParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author:luiz
 * @Date: 2018/5/28 11:16
 * @Descripton:支付宝查询接口
 * @Modify :
 * https://docs.open.alipay.com/api_1/alipay.trade.query
 **/
@Service
public class AliPayTradeQuery extends AbstractAliPay implements ChannelCore {

    private static final Logger logger= LoggerFactory.getLogger(AliPayTradeQuery.class);

   @Autowired
   ChannelConstant channelConstant;


    @Override
    public boolean isSupport(PayProductEnum payProductEnum, ChannelActionEnum channelActionEnum, ChannelInfoEnum channelInfoEnum) {
        return ChannelActionEnum.ORDER_QEURY.equals(channelActionEnum) && ChannelInfoEnum.ALIPAY.equals(channelInfoEnum);
    }


    @Override
    protected String getTradeMethod() {
        return "alipay.trade.query";
    }

    @Override
    public Map buildSelfReqParam(MerChannelDto merChannelDto, ChannelReqParam channelReqParam) {
        Map queryReqMap=new HashMap();
        JSONObject bizContent=new JSONObject();
        bizContent.put("out_trade_no", merChannelDto.getInnerSeqNo());
        queryReqMap.put("biz_content",bizContent.toString());
        return queryReqMap;
    }

    @Override
    protected ChannelRespParam buildSelfRespData(JSONObject respJson, MerChannelDto merChannelDto) {
        ChannelRespParam channelRespParam=new ChannelRespParam();
        channelRespParam.setRespCode(ChannelCodeEnum.SUCCESS.getCode());
        channelRespParam.setRespMsg(ChannelCodeEnum.SUCCESS.getName());
        String code=respJson.getString("code");
        String msg=respJson.getString("msg");
        ChannelQueryRespDto channelQueryRespDto =new ChannelQueryRespDto();
        if("40004".equals(code)){
            logger.info("【支付宝查询交易】接口调用业务失败:{}",respJson);
            channelRespParam.setRespCode(ChannelCodeEnum.SUCCESS.getCode());
            channelRespParam.setRespMsg(msg);
            String subCode=respJson.getString("sub_code");
            channelQueryRespDto.setRetCode(subCode);
            channelQueryRespDto.setRetMsg(respJson.getString("sub_msg"));
            channelQueryRespDto.setThirdTradeNo(respJson.getString("trade_no"));
            if("ACQ.TRADE_NOT_EXIST".equals(subCode)){//付款不存在则关闭
                channelQueryRespDto.setTradeStatus(PayStatusEnum.PAY_INIT);
            }
            channelQueryRespDto.setOrignRespContent(respJson);
            channelRespParam.setRespContent(JSONObject.toJSONString(channelQueryRespDto));
            return channelRespParam;
        }
        channelQueryRespDto.setThirdTradeNo(respJson.getString("trade_no"));
        channelQueryRespDto.setInnerSeqNo(respJson.getString("out_trade_no"));
        channelQueryRespDto.setBuylerId(respJson.getString("buyer_logon_id"));
        /**
         * 交易状态：WAIT_BUYER_PAY（交易创建，等待买家付款）、TRADE_CLOSED（未付款交易超时关闭，或支付完成后全额退款）、TRADE_SUCCESS（交易支付成功）、TRADE_FINISHED（交易结束，不可退款）
         */
        String tradeStatus=respJson.getString("trade_status");
        channelQueryRespDto.setRetCode(tradeStatus);
        if("WAIT_BUYER_PAY".equals(tradeStatus)){
            channelQueryRespDto.setTradeStatus(PayStatusEnum.PAY_INIT);
        }else if("TRADE_CLOSED".equals(tradeStatus)){
            channelQueryRespDto.setTradeStatus(PayStatusEnum.PAY_CLOSE);
        }else if("TRADE_SUCCESS".equals(tradeStatus)){
            channelQueryRespDto.setTradeStatus(PayStatusEnum.PAY_SUCCESS);
        }else if("TRADE_FINISHED".equals(tradeStatus)){
            channelQueryRespDto.setTradeStatus(PayStatusEnum.PAY_FINISH);
        }
        String totalAmt=respJson.getString("total_amount");
        channelQueryRespDto.setTradeAmt(new BigDecimal(totalAmt));
        channelRespParam.setRespContent(JSONObject.toJSONString(channelQueryRespDto));
        return channelRespParam;
    }


}
